# 导入所需的库
import jieba
from wordcloud import WordCloud
import matplotlib.pyplot as plt

# 读取《西游记》文本内容
with open('西游记.txt', 'r', encoding='utf-8') as file:
    text = file.read()

# 使用 jieba 进行分词
seg_list = jieba.lcut(text)

# 创建空字典保存词频统计结果
word_freq = {}
for word in seg_list:
    if len(word) > 1:  # 过滤掉单个字的词语
        word_freq[word] = word_freq.get(word, 0) + 1

# 根据词频生成词云
wc = WordCloud(font_path='simhei.ttf', background_color='white', width=800, height=600)
wc.generate_from_frequencies(word_freq)

# 显示词云图
plt.figure(figsize=(10, 8))
plt.imshow(wc)
plt.axis('off')
plt.show()
